/*
 * Copyright (C) 2011 4th Line GmbH, Switzerland
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.logging.Logger;

import org.teleal.cling.controlpoint.ActionCallback;
import org.teleal.cling.model.action.ActionException;
import org.teleal.cling.model.action.ActionInvocation;
import org.teleal.cling.model.meta.Service;
import org.teleal.cling.model.types.ErrorCode;
import org.teleal.cling.model.types.UnsignedIntegerFourBytes;
import org.teleal.cling.support.contentdirectory.DIDLParser;
import org.teleal.cling.support.model.BrowseResult;
import org.teleal.cling.support.model.DIDLContent;

/**
 * This is an implementation of the Search action. 
 */
public abstract class Search extends ActionCallback
{

	public static final String CAPS_WILDCARD = "*";
	private SearchInfo info;

	public enum Status 
	{
		NO_CONTENT("No Content"), LOADING("Loading..."), OK("OK");

		private String defaultMessage;

		Status(String defaultMessage)
		{
			this.defaultMessage = defaultMessage;
		}

		public String getDefaultMessage()
		{
			return this.defaultMessage;
		}
	}

	private static Logger log = Logger.getLogger(Search.class.getName());
	
	/**
	 * @param service 
	 * 		Should be a content directory service
	 * @param containerId
	 * @param searchCriteria
	 * @param info
	 */
	public Search(Service service, String containerId,
			SearchCriteria searchCriteria, SearchInfo info)
	{
		super(new ActionInvocation(service.getAction("Search")));

		log.fine("Creating browse action for container ID: " + containerId);

		getActionInvocation().setInput("ContainerID", containerId);
		getActionInvocation().setInput("SearchCriteria",
				searchCriteria.toString());
		getActionInvocation().setInput("Filter", "*");
		getActionInvocation().setInput("StartingIndex",
				new UnsignedIntegerFourBytes(0));
		getActionInvocation().setInput("RequestedCount",
				new UnsignedIntegerFourBytes(getDefaultMaxResults()));
		getActionInvocation().setInput("SortCriteria", "");

		this.info = info;
	}

	@Override
	public void run()
	{
		updateStatus(Status.LOADING);
		super.run();
	}

	@Override
	public void success(ActionInvocation actionInvocation)
	{
		log.fine("Successful search action, reading output argument values");

		BrowseResult result = new BrowseResult(actionInvocation
				.getOutput("Result").getValue().toString(),
				(UnsignedIntegerFourBytes) actionInvocation.getOutput(
						"NumberReturned").getValue(),
				(UnsignedIntegerFourBytes) actionInvocation.getOutput(
						"TotalMatches").getValue(),
				(UnsignedIntegerFourBytes) actionInvocation.getOutput(
						"UpdateID").getValue());

		boolean proceed = receivedRaw(actionInvocation, result);

		if (proceed && result.getCountLong() > 0
				&& result.getResult().length() > 0)
		{
			try
			{
				DIDLParser didlParser = new DIDLParser();
				DIDLContent didl = didlParser.parse(result.getResult());
				for(int i = 0; i < didl.getItems().size(); i++)
				{
					info.addRes(didl.getItems().get(i).getResources().get(0).getValue());
				}			
				received(actionInvocation, didl);
				info.setDone(true);
				updateStatus(Status.OK);
			} catch (Exception ex)
			{
				actionInvocation.setFailure(new ActionException(
						ErrorCode.ACTION_FAILED,
						"Can't parse DIDL XML response: " + ex, ex));
				failure(actionInvocation, null);
			}
		} else
		{
			received(actionInvocation, new DIDLContent());
			updateStatus(Status.NO_CONTENT);
		}
	}

	/**
	 * Some media servers will crash if there is no limit on the maximum number
	 * of results.
	 * 
	 * @return The default limit, 999.
	 */
	public Long getDefaultMaxResults()
	{
		return 999L;
	}

	public boolean receivedRaw(ActionInvocation actionInvocation,
			BrowseResult searchResult)
	{
		return true;
	}

	public abstract void received(ActionInvocation actionInvocation,
			DIDLContent didl);

	public abstract void updateStatus(Status status);
}
